package com.yjhb.android.sbz.fragment;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yjhb.android.sbz.BuildConfig;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.tool.InvitationCodeTool;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.PosterFactory;
import com.yjhb.android.sbz.tool.SharePopup;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.tool.URLConfig;
import com.jojo.android.zxlib.base.BaseFragment;
import com.jojo.android.zxlib.base.mvp.BasePresenter;
import com.jojo.android.zxlib.tool.ZxFileTool;
import com.jojo.android.zxlib.tool.ZxImageTool;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建者 zx
 * 创建时间 2020/12/3 14:30
 */
public class PostersFragment extends BaseFragment {
    private final String TAG = "InvitationFragment";
    private final String INVICODE = InvitationCodeTool.generateCode();
    private final String URL = (URLConfig.APPDownloadURL == null ? BuildConfig.APPDownloadURL : URLConfig.APPDownloadURL) + "/" + INVICODE;
    private final String PATH_SAVE = ZxFileTool.getAppSDFilePath() + "/images";
    private final String NAME = "poster.png";

    @BindView(R.id.recyclerView)
    RecyclerViewPager recyclerView;

    ILoading loadingDialog;

    //背景图
//    int[] ids = {R.mipmap.qrcode_theme1, R.mipmap.qrcode_theme2, R.mipmap.qrcode_theme3};
    Bitmap[] bitmaps = new Bitmap[PosterFactory.themeUrls.length];
    //背景图

    private int currentIndex = 0;

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_posters;
    }

    @Override
    protected void initUI() {
        loadingDialog = LoadingDialogTool.createDialog(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        initBitMap();
    }

    @Override
    protected void initEvent() {
        recyclerView.addOnPageChangedListener((oldPosition, newPosition) -> currentIndex = newPosition);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (Bitmap bitmap : bitmaps) {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
            }
        }
        bitmaps = null;
    }

    @OnClick(R.id.save_layout)
    public void save_layout() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                String path = saveQRCode(bitmaps[currentIndex]);
                emitter.onNext(path);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        if (s != null) {
                            Tool.updateGallery(getContext(), new File(s));
                            ZxToast.showINFOBottomToast("已保存:" + s);
                        } else {
                            ZxToast.showINFOBottomToast("保存失败！");
                        }
                    }
                });
    }

    @OnClick(R.id.invite_layout)
    void invite() {
        SharePopup.showSharePopup2(getActivity(), rootView, currentIndex);
    }


    private void initBitMap() {
        loadingDialog.setTipsText("正在生成...");
        loadingDialog.show();
        Observable.create((ObservableOnSubscribe<Bitmap>) e -> {
            //主题一
            bitmaps[0] = PosterFactory.Poster(getActivity(), URL, 0);
            //主题二
            bitmaps[1] = PosterFactory.Poster(getActivity(), URL, 1);
            //主题三
            bitmaps[2] = PosterFactory.Poster(getActivity(), URL, 2);

            e.onComplete();

        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Bitmap o) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ZxLogTool.err(e);
                        ZxToast.showINFOBottomToast("海报生成失败QAQ~~");
                        if (getActivity() != null)
                            getActivity().finish();
                    }

                    @Override
                    public void onComplete() {
                        recyclerView.setAdapter(new RecyclerView.Adapter() {
                            @NonNull
                            @Override
                            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                                return new ImageHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_posters, parent, false));
                            }

                            @Override
                            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                                try {
                                    if (holder instanceof ImageHolder) {
                                        ((ImageHolder) holder).bg_layout.setBackground(new BitmapDrawable(getResources(), bitmaps[position]));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public int getItemCount() {
                                return PosterFactory.themeUrls.length;
                            }
                        });
                        loadingDialog.cancel();
                    }
                });
    }

    /**
     * 保存海报
     */
    private String saveQRCode(Bitmap bitmap) {
        File dir = new File(PATH_SAVE);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, NAME);
        boolean b = ZxImageTool.save(bitmap, file, Bitmap.CompressFormat.PNG, false);
        if (b) {
            return file.getAbsolutePath();
        } else {
            return null;
        }
    }


    class ImageHolder extends RecyclerView.ViewHolder {
        //        ImageView imageView;
        FrameLayout bg_layout;

        public ImageHolder(@NonNull View itemView) {
            super(itemView);
//            imageView = itemView.findViewById(R.id.image_iv);
            bg_layout = itemView.findViewById(R.id.bg_layout);
        }
    }
}
